package zy.blue7.gui.netty.learn.simple;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author blue7
 * @version 1.0
 * @date 2022/2/25 14:53
 */
public class HelloClient {


    public static void main(String[] args) throws InterruptedException {

        /**
         * 客户端需要一个事件循环组
         */
        NioEventLoopGroup group = new NioEventLoopGroup();

        /**
         * 创建客户端启动对象
         * 注意客户端使用的不是 serverBootStarp
         */
        Bootstrap bootstrap = new  Bootstrap();


        try {

            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HelloClientHandler());//加入自己的处理器
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    System.out.println("-----");


                                    super.channelRead(ctx, msg);
                                }
                            });
                        }
                    });

            System.out.println("客户端 ok....");

            /**
             * 启动客户端去链接 服务器
             */
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8080).sync();


            channelFuture.channel().closeFuture().sync();
        }finally {

            group.shutdownGracefully();
        }



    }
}
